package ie.dcu.spca.model;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

public class DBconnection {
    // private String dbName = "mydb";
    private SQLiteDatabase sdb = null;
    private static DBconnection dbc = null;

    public static DBconnection getInstance() {
        return dbc;
    }

    public static void makeInstance(Context cont, String dbName) {
        dbc = new DBconnection(cont, dbName);
    }

    private DBconnection(Context cont, String dbName) {
        // this.sdb = SQLiteDatabase.openOrCreateDatabase(dbName, null);
        this.sdb = cont
                .openOrCreateDatabase(dbName, Context.MODE_PRIVATE, null);
    }

    public void closedb() {
        this.sdb.close();
    }

    public void executeSql(String sql, Object[] objs) {
        SQLiteStatement stmt = this.sdb.compileStatement(sql);
        for(int i=0;i<objs.length;i++){
           Object o = objs[i];
           int index = i+1;
           if(o instanceof Double){
               stmt.bindDouble(index, (Double)o);
           }else if(o instanceof Integer){
               stmt.bindLong(index, (Integer)o);
           }else if(o instanceof String){
               stmt.bindString(index, (String)o);
           }else if(o instanceof Long){
               stmt.bindLong(index, (Long)o);
           }
        }
        //this.sdb.execSQL(sql);
        stmt.execute();
    }

    public Cursor querySql(String sql) {
        return this.sdb.rawQuery(sql, null);
    }
}
